// 2 insert操作支持返回主键，写个例子。

import jdbc527.DBUtil;

import java.sql.*;
import java.util.Scanner;

public class ReturnKey {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Scanner sc = new Scanner(System.in);
        try {
            con = DBUtil.getConnection();
            System.out.println("输入姓名");
            //设置返回主键
            ps = con.prepareStatement("insert into s_student(sname,gradeid)values (?,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, sc.next());
            int i = ps.executeUpdate();
            System.out.println(i > 0 ? "成功" : "失败");
            //获取返回的主键
            rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println("id:" + rs.getInt(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, ps, con);
        }
    }
}